package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.service.IAlertRuleService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 报警规则管理Service业务层处理
 *
 * @author guomo
 * @date 2025-10-20
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {

    @Value("${alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;

    @Value("${alert.managerRole}")
    private String managerRole;

    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ScriptEngine scriptEngine;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private IAlertDataService dataService;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 查询报警规则管理
     *
     * @param id 报警规则管理主键
     * @return 报警规则管理
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警规则管理列表
     * @param alertRule 报警规则管理
     * @return 报警规则管理
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则管理
     *
     * @param alertRule 报警规则管理
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return save(alertRule) ? 1 : 0;
    }

    /**
     * 修改报警规则管理
     *
     * @param alertRule 报警规则管理
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return updateById(alertRule) ? 1 : 0;
    }

    /**
     * 批量删除报警规则管理
     *
     * @param ids 需要删除的报警规则管理主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警规则管理信息
     *
     * @param id 报警规则管理主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void alertFilter() {

        //查询所有的规则
        LambdaQueryWrapper<AlertRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AlertRule::getStatus, 1);
        List<AlertRule> list = this.list(queryWrapper);
        if (CollUtil.isEmpty(list)) {
            return;
        }

        //从redeis中获取最新的设备上报数据
        List<Object> deviceDateList = redisTemplate.boundHashOps(CacheConstants.IOT_DEVICE_LAST_DATA).values();
        if (CollUtil.isEmpty(deviceDateList)) {
            return;
        }
        //数据标准化处理
        List<DeviceData> dataList = new ArrayList<>();
        for (Object object : deviceDateList) {
            List<DeviceData> deviceData = JSONUtil.toList(object.toString(), DeviceData.class);
            dataList.addAll(deviceData);
        }

        for (DeviceData deviceData : dataList) {
            //开始循环遍历上报数据
            alterFilter(deviceData);
        }


    }

    /**
     * 查询指定设备的状态为激活的所有规则，并根据设备的功能ID和IoT ID进行筛选。
     * 合并查询结果，并对每个规则执行设备数据告警处理。
     *
     * @param deviceData 设备数据对象，包含功能ID和IoT ID。
     */
    private void alterFilter(DeviceData deviceData) {

        //查询此设备全部的规则
        LambdaQueryWrapper<AlertRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AlertRule::getStatus, 1);
        queryWrapper.eq(AlertRule::getFunctionId, deviceData.getFunctionId());
        queryWrapper.eq(AlertRule::getIotId, -1);
        List<AlertRule> list = this.list(queryWrapper);

        //查询此设备的规则
        LambdaQueryWrapper<AlertRule> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(AlertRule::getStatus, 1);
        queryWrapper1.eq(AlertRule::getFunctionId, deviceData.getFunctionId());
        queryWrapper1.eq(AlertRule::getIotId, deviceData.getIotId());
        List<AlertRule> list1 = this.list(queryWrapper1);

        Collection<AlertRule> ruleCollection = CollUtil.addAll(list, list1);
        if (CollUtil.isEmpty(ruleCollection)) {
            return;
        }

        for (AlertRule alertRule : ruleCollection) {
            deviceDataAlarmHandler(alertRule, deviceData);
        }


    }

    /**
     * 处理设备数据报警，根据规则判断是否触发报警。
     * @param alertRule 报警规则对象，包含报警的有效时间段、阈值等。
     * @param deviceData 设备数据对象，包含设备的报警时间、IoT ID、产品Key等。
     * @throws ScriptException 如果表达式计算出错，将抛出此异常。
     */
    private void deviceDataAlarmHandler(AlertRule alertRule, DeviceData deviceData) {
        log.info("进入第一层校验");
        //判断报警时间是否在规则设定期间
        String period = alertRule.getAlertEffectivePeriod();
        String[] periodSplit = period.split("~");
        LocalTime startTime = LocalTime.parse(periodSplit[0]);
        LocalTime alertTime = deviceData.getAlarmTime().toLocalTime();
        LocalTime endTime = LocalTime.parse(periodSplit[1]);
        if (alertTime.isBefore(startTime) || alertTime.isAfter(endTime)) {
            return;
        }
        log.info("进入第二层校验");
        //拼接表达式 计算是否超出阈值
        String alertCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + deviceData.getIotId() + deviceData.getProductKey() + alertRule.getFunctionId() + alertRule.getId();
        String slientKey = CacheConstants.ALERT_SILENT_PREFIX + deviceData.getIotId() + deviceData.getProductKey() + alertRule.getFunctionId() + alertRule.getId();

        String expression = deviceData.getDataValue() + alertRule.getOperator() + alertRule.getValue();
        boolean flag = false;
        try {
            flag = (boolean) scriptEngine.eval(expression);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
        if (!flag) {
            redisTemplate.delete(alertCountKey);
            return;
        }

        log.info("进入第三层校验");
        String slien = redisTemplate.boundValueOps(slientKey).get();
        if (slien != null) {
            return;
        }

        log.info("进入第四次校验");
        Long alertCount = redisTemplate.boundValueOps(alertCountKey).increment();

        if (alertCount < alertRule.getDuration()) {
            return;
        }

        log.info("触发报警");
        //删除redis报警数
        redisTemplate.delete(alertCountKey);
        //添加沉默周期
        redisTemplate.boundValueOps(slientKey).set("沉默周期", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        log.info("校验通过");
        insertAlertData(alertRule, deviceData);


    }


    /**
     * 插入报警数据到数据库。
     * 根据设备类型和位置信息，查询相关用户的ID，然后创建报警数据列表并保存。
     *
     * @param alertRule 报警规则对象，包含报警的相关规则信息。
     * @param deviceData 设备数据对象，包含设备的各种属性信息。
     *
     * @throws Exception 如果查询用户ID或保存报警数据时发生错误。
     */
    private void insertAlertData(AlertRule alertRule, DeviceData deviceData) {
        //随身设备
        List<Long> userids = new ArrayList<>();
        if (deviceData.getLocationType().equals(0)) {
            userids = deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());
        } else {
            //固定设备
            if (deviceData.getPhysicalLocationType().equals(1)) {
                userids = sysUserRoleMapper.selectUserIdByRoleName(deviceMaintainerRole);

            } else if (deviceData.getPhysicalLocationType().equals(2)) {
                userids = deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            }
        }
        List<Long> admins = sysUserRoleMapper.selectUserIdByRoleName(managerRole);
        Collection<Long> ids = CollUtil.addAll(userids, admins);
        ArrayList<Long> distinctids = CollUtil.distinct(ids);
        List<AlertData> alertDataList = new ArrayList<>();
        for (Long distinctid : distinctids) {
            AlertData alertData = new AlertData();
            alertData.setIotId(deviceData.getIotId());
            alertData.setDeviceName(deviceData.getDeviceName());
            alertData.setProductKey(deviceData.getProductKey());
            alertData.setProductName(deviceData.getProductName());
            alertData.setFunctionId(deviceData.getFunctionId());
            alertData.setAccessLocation(deviceData.getAccessLocation());
            alertData.setLocationType(deviceData.getLocationType());
            alertData.setPhysicalLocationType(deviceData.getPhysicalLocationType());
            alertData.setDeviceDescription(deviceData.getDeviceDescription());
            alertData.setDataValue(deviceData.getDataValue());
            alertData.setAlertRuleId(alertRule.getId());
            /** 报警原因，格式：功能名称+运算符+阈值+持续周期+沉默周期 */
            String reason = deviceData.getFunctionId() + alertRule.getOperator() + alertRule.getValue() + alertRule.getDuration() + alertRule.getAlertSilentPeriod();
            alertData.setAlertReason(reason);

            alertData.setType(deviceData.getLocationType());
            alertData.setStatus(0);
            alertData.setUserId(distinctid);
            alertDataList.add(alertData);
        }
        dataService.saveBatch(alertDataList);
        websocketNotity(alertDataList.get(0), alertRule, distinctids);
    }

    private void websocketNotity(AlertData alertData, AlertRule alertRule, List<Long> distinctids) {
        AlertNotifyVo alertNotifyVo = new AlertNotifyVo();
        alertNotifyVo.setAccessLocation(alertData.getAccessLocation());
        alertNotifyVo.setLocationType(alertData.getLocationType());
        alertNotifyVo.setPhysicalLocationType(alertData.getPhysicalLocationType());
        alertNotifyVo.setDeviceDescription(alertData.getDeviceDescription());
        alertNotifyVo.setProductName(alertData.getProductName());
        alertNotifyVo.setFunctionName(alertRule.getFunctionName());
        alertNotifyVo.setDataValue(alertData.getDataValue());
        alertNotifyVo.setAlertDataType(alertRule.getAlertDataType());
        alertNotifyVo.setVoiceNotifyStatus(0);
        alertNotifyVo.setNotifyType(1);
        alertNotifyVo.setIsAllConsumer(false);
        webSocketServer.sendMessageToConsumer(alertNotifyVo,distinctids);
    }
}
